<?php
/**
 * VIP订单管理逻辑层（后台专用）
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\admin\logic;

use app\common\logic\Vip as CommonVip;

class VipOrder extends AdminBase
{
    /**
     * @var CommonVip
     */
    public static $commonVipLogic;
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        
        empty(static::$commonVipLogic) && static::$commonVipLogic = new CommonVip();
    }
    
    /**
     * VIP订单管理
     */
    public function vipOrderManage($data = [])
    {
        // 处理批量操作
        if (!empty($data['ids']) && !empty($data['type'])) {
            $ids = explode(',', $data['ids']);
            $result = true;
            
            foreach ($ids as $id) {
                switch ($data['type']) {
                    case 'activate':
                        $result = $this->vipOrderStatus(['id' => $id, 'status' => 1]);
                        break;
                    case 'cancel':
                        $result = $this->vipOrderStatus(['id' => $id, 'status' => 2]);
                        break;
                    case 'delete':
                        $result = $this->modelVipOrder->deleteInfo(['id' => $id]);
                        break;
                }
                
                if (!$result) {
                    break;
                }
            }
            
            return $result ? [RESULT_SUCCESS, '批量操作成功'] : [RESULT_ERROR, '批量操作失败'];
        }
        
        return [RESULT_SUCCESS, 'VIP订单管理'];
    }
    
    /**
     * 获取VIP订单搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        if (!empty($data['user_id'])) {
            $where['vo.user_id'] = $data['user_id'];
        }
        
        // 订单号搜索
        if (!empty($data['order_no'])) {
            $where['vo.order_no'] = ['like', '%' . $data['order_no'] . '%'];
        }
        
        // 支付状态搜索
        if (isset($data['status']) && $data['status'] !== '') {
            $where['vo.status'] = $data['status'];
        }
        
        // 套餐类型搜索
        if (!empty($data['package_type'])) {
            $where['vo.package_type'] = $data['package_type'];
        }
        
        // 用户昵称和手机号搜索
        if (!empty($data['search_data'])) {
            $where['u.nickname|u.mobile'] = ['like', '%' . $data['search_data'] . '%'];
        }
        
        // 时间范围搜索
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where['vo.create_time'] = ['between', [strtotime($data['start_time']), strtotime($data['end_time'])]];
        }
        
        return $where;
    }
    
    /**
     * 获取VIP订单列表
     */
    public function getVipOrderList($where = [], $field = true, $order = 'vo.id desc', $paginate = DB_LIST_ROWS)
    {
        // 设置别名和关联查询
        $this->modelVipOrder->alias_name = 'vo';
        $this->modelVipOrder->join = [
            ['user u', 'u.id = vo.user_id', 'LEFT']
        ];
        
        // 如果field为true，设置默认字段
        if ($field === true) {
            $field = 'vo.*, u.nickname, u.mobile, u.avatar_url';
        }
        
        $list = $this->modelVipOrder->getList($where, $field, $order, $paginate);
        
        // 清理属性，避免影响后续查询
        $this->modelVipOrder->join = [];
        $this->modelVipOrder->alias_name = '';
        
        return $list;
    }
    
    /**
     * 获取VIP订单详情
     */
    public function getVipOrderInfo($where = [], $field = true)
    {
        // 设置主表别名
        $this->modelVipOrder->alias_name = 'vo';
        
        // 设置关联查询
        $this->modelVipOrder->join = [
            ['user u', 'u.id = vo.user_id', 'LEFT']
        ];
        
        // 设置查询字段
        if ($field === true) {
            $field = 'vo.*, u.nickname, u.mobile, u.avatar_url, u.create_time as user_create_time';
        }
        
        $info = $this->modelVipOrder->getInfo($where, $field);
        
        // 清理属性
        $this->modelVipOrder->join = [];
        $this->modelVipOrder->alias_name = '';
        
        return $info;
    }
    
    /**
     * VIP订单状态管理
     */
    public function vipOrderStatus($data = [])
    {
        $where = ['id' => $data['id']];
        $update = [
            'order_status' => $data['status'],
            'update_time' => time()
        ];
        
        // 如果是设置为已支付状态，更新支付时间
        if ($data['status'] == 1) {
            $update['pay_time'] = time();
        }
        
        $result = $this->modelVipOrder->updateInfo($where, $update);
        
        if ($result) {
            action_log('VIP订单状态', 'VIP订单状态管理，id：' . $data['id'] . '，order_status：' . $data['status']);
            
            // 如果订单状态改为已支付，需要激活用户VIP
            if ($data['status'] == 1) {
                $orderInfo = $this->modelVipOrder->getInfo(['id' => $data['id']]);
                if ($orderInfo) {
                    // 调用common层激活VIP逻辑
                    static::$commonVipLogic->activateVipByOrder($orderInfo);
                }
            }
        }
        
        return $result ? [RESULT_SUCCESS, 'VIP订单状态更新成功'] : [RESULT_ERROR, $this->modelVipOrder->getError()];
    }
    
    /**
     * 获取VIP订单统计
     */
    public function getVipOrderStats($data = [])
    {
        $stats = [];
        
        // 总订单数
        $stats['total_orders'] = $this->modelVipOrder->stat([], 'count');
        
        // 已支付订单数
        $stats['paid_orders'] = $this->modelVipOrder->stat(['status' => 1], 'count');
        
        // 待支付订单数
        $stats['pending_orders'] = $this->modelVipOrder->stat(['status' => 0], 'count');
        
        // 总收入
        $stats['total_income'] = $this->modelVipOrder->getValue(['status' => 1], 'SUM(amount)') ?: 0;
        
        // 今日订单数
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        $stats['today_orders'] = $this->modelVipOrder->stat([
            'create_time' => ['between', [$todayStart, $todayEnd]]
        ], 'count');
        
        // 今日收入
        $stats['today_income'] = $this->modelVipOrder->getValue([
            'status' => 1,
            'create_time' => ['between', [$todayStart, $todayEnd]]
        ], 'SUM(amount)') ?: 0;
        
        return $stats;
    }
    
    /**
     * 导出VIP订单列表
     */
    public function exportVipOrderList($where = [])
    {
        try {
            // 设置关联查询
            $this->modelVipOrder->alias_name = 'vo';
            $this->modelVipOrder->join = [
                ['user u', 'u.id = vo.user_id', 'LEFT']
            ];
            
            $field = 'vo.id,vo.order_no,vo.package_type,vo.package_name,vo.amount,vo.status,vo.transaction_id,vo.create_time,vo.pay_time,u.nickname,u.mobile';
            $order = 'vo.id desc';
            
            $list = $this->modelVipOrder->getList($where, $field, $order, false);
            
            // 清理属性
            $this->modelVipOrder->join = [];
            $this->modelVipOrder->alias_name = '';
            
            // 处理导出数据
            $exportData = [];
            foreach ($list as $item) {
                $exportData[] = [
                    'ID' => $item['id'],
                    '订单号' => $item['order_no'],
                    '用户昵称' => $item['nickname'] ?: '未设置',
                    '手机号' => $item['mobile'] ?: '未绑定',
                    '套餐类型' => $item['package_type'],
                    '套餐名称' => $item['package_name'],
                    '金额' => $item['amount'],
                    '支付状态' => $this->getStatusText($item['status']),
                    '交易号' => $item['transaction_id'] ?: '-',
                    '创建时间' => date('Y-m-d H:i:s', $item['create_time']),
                    '支付时间' => $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '-'
                ];
            }
            
            // TODO: 实现Excel导出功能
            return [RESULT_SUCCESS, '导出成功', $exportData];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('导出VIP订单列表失败：' . $e->getMessage());
            return [RESULT_ERROR, '导出失败'];
        }
    }
    
    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            0 => '待支付',
            1 => '已支付',
            2 => '已取消',
            3 => '已退款'
        ];
        
        return $statusMap[$status] ?? '未知';
    }
}